// node 15_字符串算法_输出特定树状结构.js

//Boolean ?

//输入字符串: '[abc[bcd[efg]]]'
//得到目标结构:
// {
//     value: 'abc',
//     children: { 
//         value: 'bcd', 
//         children: { 
//             value: 'efg' 
//                     } 
//                 }
//   }

let myString = '[abc[bcd[efg]]]'

//方法1:
function operateString1(s) {
    // let arr = s.split(/[\[\]]/g).filter(e => e)
    // let arr = s.split(/[\[\]]/g).filter(Boolean)
    let arr = s.match(/\w+/g)
    console.log(arr)
    let obj = {}
    let head = obj//头节点
    while(true){
        obj.value = arr.shift()
        if(!arr.length) break;
        obj.children = {}
        obj = obj.children //下一项
    }
    return head
}

function operateString2(s) {
    let arr = s.split(/[\[\]]/g).filter(e => e)
    let head = {}
    arr.reduce((pre,data,index,arr)=>{
        pre.value = data
        if(index != arr.length-1) return pre.children = {}
    },head)
    return head
}

console.log('方法1:')
console.log(operateString1(myString))
console.log('方法2:')
console.log(operateString2(myString))